package com.example.forumsystem.demos.web.controller;

import com.example.forumsystem.demos.web.common.Constans;
import com.example.forumsystem.demos.web.common.ResultCode;
import com.example.forumsystem.demos.web.exception.ApplicationException;
import com.example.forumsystem.demos.web.model.ArticleInfo;
import com.example.forumsystem.demos.web.model.ArticleReplyInfo;
import com.example.forumsystem.demos.web.model.Result;
import com.example.forumsystem.demos.web.model.UserInfo;
import com.example.forumsystem.demos.web.service.IArticleReplyService;
import com.example.forumsystem.demos.web.service.IArticleService;
import io.micrometer.core.lang.NonNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "帖子回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Autowired
    private IArticleReplyService articleReplyService;
    @Autowired
    private IArticleService articleServicer;

    @ApiOperation("新增回复")
    @RequestMapping("/create")
    public Result create (HttpServletRequest request,
                        @ApiParam("帖子Id") @RequestParam("articleId") @NonNull Long articleId,
                        @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {

        HttpSession session = request.getSession(false);
        UserInfo user = (UserInfo) session.getAttribute(Constans.USER_SESSION);
        // 如果用户是禁言状态，直接返回失败
        if (user.getState() == 1) {
            return Result.fail();
        }

        ArticleReplyInfo articleReply = new ArticleReplyInfo();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReplyService.create(articleReply);
        return Result.success();
    }

    @ApiOperation("获取回复列表")
    @RequestMapping("/getReplies")
    public List<ArticleReplyInfo> getRepliesByArticleId (@ApiParam("帖子Id") @RequestParam("articleId") @NonNull Long articleId) {
        // 校验帖子是否存在
        ArticleInfo article = articleServicer.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn("帖子不存在或者帖子是删除状态");
            throw new ApplicationException(Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        List<ArticleReplyInfo> articleReplies = articleReplyService.selectByArticleId(articleId);
        if (articleReplies == null){
            articleReplies = new ArrayList<>();
        }
        return articleReplies;
    }
}